import java.util.*;

public class BinaryTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    /**
     * 手动创建二叉树，创建完成之后，返回根节点
     * @return
     */
    public TreeNode createTree() {
        TreeNode A = new TreeNode(1);
        TreeNode B = new TreeNode(1);
        TreeNode C = new TreeNode(1);
        TreeNode D = new TreeNode(1);
        TreeNode E = new TreeNode(1);
        TreeNode F = new TreeNode(1);
        TreeNode G = new TreeNode(1);
        TreeNode H = new TreeNode(1);
        TreeNode I = new TreeNode(1);
        TreeNode J = new TreeNode(1);
        TreeNode K = new TreeNode(1);
        TreeNode L = new TreeNode(2);



        A.right = B;
        B.right = C;
        C.right = D;
        D.right = E;
        E.right = F;
        F.right = G;
        G.right = H;
        H.right = I;
        I.right = J;
        J.left = K;
        J.right = L;

        return A;
    }

    public TreeNode createTree2() {
        TreeNode F = new TreeNode(1);
        TreeNode G = new TreeNode(1);
        TreeNode H = new TreeNode(1);
        TreeNode I = new TreeNode(1);
        TreeNode J = new TreeNode(1);
        TreeNode K = new TreeNode(1);
        TreeNode L = new TreeNode(2);

        F.right = G;
        G.right = H;
        H.right = I;
        I.right = J;
        J.left = K;
        J.right = L;

        return F;
    }

    public TreeNode createTree3() {
        TreeNode A = new TreeNode(1);
        TreeNode B = new TreeNode(2);
        TreeNode C = new TreeNode(2);
        TreeNode D = new TreeNode(3);
        TreeNode E = new TreeNode(4);
        TreeNode F = new TreeNode(4);
        TreeNode G = new TreeNode(3);

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;

        return A;
    }

    public TreeNode createTree4() {
        TreeNode A = new TreeNode(3);
        TreeNode B = new TreeNode(9);
        TreeNode C = new TreeNode(20);
        TreeNode D = new TreeNode(15);
        TreeNode E = new TreeNode(7);

        A.left = B;
        A.right = C;
        C.left = D;
        C.right = E;
        return A;
    }

    public TreeNode createTreeForinorderTraversal() {
        TreeNode A = new TreeNode(1);
        TreeNode B = new TreeNode(2);
        TreeNode C = new TreeNode(3);

        A.right = B;
        B.left = C;

        return A;
    }

    public TreeNode createTreeForpostorderTraversal() {
        TreeNode A = new TreeNode(1);
        TreeNode B = new TreeNode(2);
        TreeNode C = new TreeNode(3);

        A.right = B;
        B.right = C;

        return A;
    }

    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        int lH = height(root.left);
        int rH = height(root.right);

        return Math.abs(lH-rH) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

    public int height(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int lH = height(root.left);
        int rH = height(root.right);

        return Math.max(lH,rH)+1;
    }

    public boolean isBalanced2(TreeNode root) {
        if(root == null) {
            return true;
        }
        return getHeight(root) >= 0;
    }

    public int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int lh = getHeight(root.left);
        if(lh < 0) {
            return -1;
        }
        int rh = getHeight(root.right);
        if(rh < 0) {
            return -1;
        }
        if(Math.abs(lh-rh) <= 1) {
            return Math.max(lh,rh)+1;
        }else {
            return -1;
        }
    }

    //判断两颗数是否相等
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p != null && q == null || p == null && q != null) {
            return false;
        }
        //走到这里的情况是什么？ 要么2个都是空 要么要个都不是空
        if(p == null && q == null) {
            return true;
        }
        if(p.val != q.val) {
            return false;
        }
        //走到这里 p != null && q != null  && p.val == q.val
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    public boolean isSubTree(TreeNode root, TreeNode subRoot) {
        if(root == null) {
            return false;
        }
        if(isSameTree(root,subRoot)) {
            return true;
        }
        if(isSubTree(root.left,subRoot)) {
            return true;
        }
        if(isSubTree(root.right, subRoot)) {
            return true;
        }
        return false;
    }


    //判断是否对称
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }

        return isSymmetricChild(root.left,root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        if(leftTree == null && rightTree != null || leftTree != null && rightTree == null) {
            return false;
        }
        if(leftTree == null && rightTree == null) {
            return true;
        }
        if(leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right) && isSymmetricChild(leftTree.right,rightTree.left);
    }

    //分层遍历（自顶向下）
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if(root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(! queue.isEmpty()) {
            List<Integer> level = new ArrayList<Integer>();
            int currentLevelSize = queue.size();
            for(int i = 1; i <= currentLevelSize; i++) {
                TreeNode cur = queue.poll();
                level.add(cur.val);

                if(cur.left != null) {
                    queue.offer(cur.left);
                }

                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            ret.add(level);
        }
        return ret;
    }


    //非递归中序遍历
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<>();
        while(root != null || !stk.isEmpty()) {
            while(root != null) {
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }


    //非递归打印后序
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if(root == null) {
            return res;
        }

        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode prev = null;

        while(root != null || !stack.isEmpty()) {
            while(root != null) {
                stack.push(root);
                root = root.left;
            }

            root = stack.pop();//从栈顶弹出的，并不为空
            if(root.right == null || root.right == prev) {
                res.add(root.val);
                prev = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }

        }

        return res;
    }


    //
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        if(root == null) {
            return stringBuilder.toString();
        }
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
        if(t == null) {
            return;
        }
        stringBuilder.append(t.val);
        //判断当前t的左边
        if(t.left != null) {
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(t.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        //判断当前t的右边
        if(t.right != null) {
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }
        if(root == p || root == q) {
            return root;
        }
        TreeNode leftV = lowestCommonAncestor(root.left,p,q);
        TreeNode rightV = lowestCommonAncestor(root.right,p,q);
        if(leftV != null && rightV != null) {
            return root;
        }else if(leftV != null) {
            return leftV;
        }else if(rightV != null) {
            return rightV;
        }
        return null;
    }


    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }

        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();

        getPath(root,p,stackP);

        getPath(root,q,stackQ);

        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        int size = sizeP - sizeQ;

        if(size < 0) {
            //第2个栈中元素多
            size = sizeQ - sizeP;
            //第2个栈 出size个元素
            while(size != 0) {
                stackQ.pop();
                size--;
            }

        }else {
            //第1个栈中元素多
            while(size != 0) {
                stackP.pop();
                size--;
            }
        }

        //代码走到这里 说明 2个栈当中 元素的个数是一样的了
        while (!stackP.isEmpty() && !stackQ.isEmpty()) {
            if(stackP.peek() == stackQ.peek()) {
                return stackP.peek();
            }else {
                stackP.pop();
                stackQ.pop();
            }
        }
        return null;
    }

    /**
     * 找到根节点 到 node节点路径上的所有节点 ，存储到栈当中
     * @param root
     * @param node
     * @param stack
     */
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if(root == null || node == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean flg = getPath(root.left,node,stack);
        if(flg) {
            return true;
        }
        boolean flg2 = getPath(root.right,node,stack);
        if(flg2) {
            return true;
        }
        stack.pop();
        return false;
    }

    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        if(root == null) {
            return stringBuilder.toString();
        }
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

}
